package com.example.baselibrary.permission;

import android.app.Activity;
import android.content.pm.PackageManager;
import androidx.annotation.Nullable;

import java.lang.ref.SoftReference;
import java.util.HashMap;

/**
 * 权限统一管理
 * create by zzx
 * create at 18-12-13
 */
public class PermissionManager {

    private static final String TAG = "PermissionManager";

    private static volatile PermissionManager sInstance;

    private SoftReference<Activity> mActivity;

    private HashMap<Integer, PermissionCallback> mCallbackMap;

    private PermissionHandler permissionHandler;

    private int initialRequestCode = 501;

    private PermissionManager() {
        mCallbackMap = new HashMap<>();
        permissionHandler = new PermissionHandler();
    }

    public static PermissionManager getInstance() {
        if (sInstance == null) {
            synchronized (PermissionManager.class) {
                if (sInstance == null) {
                    sInstance = new PermissionManager();
                }
            }
        }
        return sInstance;
    }

    public void init(@Nullable Activity activity) {
        if (mActivity != null && mActivity.get() == activity) {
            return;
        } else if (mActivity != null) {
            mActivity.clear();
        }
        mActivity = new SoftReference<>(activity);
    }

    public void handleCheck(String permission, PermissionCallback callback) {
        if (mActivity == null || mActivity.get() == null) {
            return ;
        }
        if (permissionHandler.checkPermission(mActivity.get(), permission)) {
            callback.hasAgreed();
            return ;
        }
        int request = obtainRequestCode();
        permissionHandler.requestPermission(mActivity.get(), request, permission);
        mCallbackMap.put(request, callback);
    }

    /**
     * 随机生成申请码
     * @return
     */
    private int obtainRequestCode() {
        int requestCode = initialRequestCode++ % 1000;
        if (mCallbackMap.containsKey(requestCode)) {
            return obtainRequestCode();
        } else {
            return requestCode;
        }
    }

    public void releaseContext(Activity activity) {
        if (mActivity != null && mActivity.get() == activity) {
            mActivity.clear();
        }
    }

    public boolean handleResult(int requestCode, String[] permissions, int[] grantResults) {
        if (!mCallbackMap.containsKey(requestCode)) {
            return false;
        }
        PermissionCallback callback = mCallbackMap.get(requestCode);
        if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
            callback.reject();
        } else {
            callback.agree();
        }
        mCallbackMap.remove(requestCode);
        return true;
    }
}
